package com.dev.dream.exochatlockscreen;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import shared.ui.actionscontentview.ActionsContentView;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.net.ParseException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.dev.dream.exochatlockscreen.service.SLockscreen;
import com.dev.dream.exochatlockscreen.slidemenu.HelpFragment;
import com.dev.dream.exochatlockscreen.slidemenu.HomeFragment;
import com.dev.dream.exochatlockscreen.slidemenu.SettingsFragment;
import com.dev.dream.exochatlockscreen.slidemenu.SettingsReceiveMsgFragment;
import com.dev.dream.exochatlockscreen.slidemenu.SettingsSendMsgFragment;
import com.dev.dream.libs.adapter.app.AppController;
import com.dev.dream.libs.checknetwork.CheckNetword;
import com.dev.dream.libs.share.MyShare;
import com.dev.dream.libs.slidemenu.adapter.SlideMenuAdapter;
import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppSDK;

public class Activity extends FragmentActivity {

	private ActionsContentView viewActionsContentView;

	TextView tvTitleMenu;

	int width, height;

	private SharedPreferences pre;
	private StartAppAd startAppAd;

	String click_ad1 = "ad1_20102014";
	String click_ad2 = "ad2_20102014";

	Handler handler_timer = new Handler();

	public Runnable update_time = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			// time++;
			// if (time > timeDelay) {
			startAppAd.show();
			startAppAd.load();
			// time = 0;
			// }
			// Log.d("kai", "chay");
			handler_timer.postDelayed(update_time, 1000 * 60);
		}
	};

	String KEY_ADS = "KEY_ADS";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		CalligraphyConfig.initDefault("fonts/ttt.ttf", R.attr.fontPath);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_new_main);

		pre = getSharedPreferences("dev.dream.exochatlockscreen.ads",
				MODE_PRIVATE);

		StartAppSDK.init(this, "111076217 ", "210808285", true);
		startAppAd.showSplash(this, savedInstanceState);
		StartAppAd.showSlider(this);
		startAppAd = new StartAppAd(this);

		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		height = displaymetrics.heightPixels;
		width = displaymetrics.widthPixels;

		EXOChatKeypadPreferences.getInstance().initPreferences(this);

		if (SLockscreen.instance == null) {

			startService(new Intent(getApplicationContext(), SLockscreen.class));

		}

		viewActionsContentView = (ActionsContentView) findViewById(R.id.actionsContentView);

		final ListView viewActionsList = (ListView) findViewById(R.id.actions);

		tvTitleMenu = (TextView) findViewById(R.id.tv_titleMenu);

		String[] mTitles = getResources().getStringArray(R.array.actions_names);
		String[] mType = getResources().getStringArray(R.array.actions_type);

		TypedArray iconsArray = getResources().obtainTypedArray(
				R.array.actions_icons);
		int count = iconsArray.length();
		int[] mIcons = new int[count];
		for (int i = 0; i < count; ++i) {
			mIcons[i] = iconsArray.getResourceId(i, 0);
		}
		iconsArray.recycle();

		SlideMenuAdapter actionsAdapter = new SlideMenuAdapter(

		getApplicationContext(), mTitles, mType, mIcons);

		viewActionsList.setAdapter(actionsAdapter);
		viewActionsList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> adapter, View v,
							int position, long flags) {
						showFragment(position);
					}
				});

		if (CheckNetword.checkInternetConnection(getApplicationContext())) {

			new JSONAsyncTask()
					.execute("http://devdreamvn.somee.com/largekpopads.json");

		}

		showFragment(0);

	}

	String idApp, urlApp, urlImage;

	class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			// dialog.setTitle("Connecting server");

		}

		@Override
		protected Boolean doInBackground(String... urls) {
			try {

				// ------------------>>
				Log.d("Kai", "Start");
				HttpGet httppost = new HttpGet(urls[0]);
				HttpClient httpclient = new DefaultHttpClient();
				HttpResponse response = httpclient.execute(httppost);

				// StatusLine stat = response.getStatusLine();
				int status = response.getStatusLine().getStatusCode();

				if (status == 200) {
					HttpEntity entity = response.getEntity();
					String data = EntityUtils.toString(entity);

					JSONObject jsono = new JSONObject(data);
					JSONArray jarray = jsono.getJSONArray("apps");

					for (int i = 0; i < jarray.length(); i++) {
						JSONObject object = jarray.getJSONObject(i);

						idApp = object.getString("id");

						urlApp = object.getString("url");

						urlImage = object.getString("urlicon");

					}
					return true;
				}

				// ------------------>>

			} catch (ParseException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return false;
		}

		protected void onPostExecute(Boolean result) {

			if (!pre.getString(KEY_ADS, "23012991").equals(idApp)) {
				showPopup(Activity.this);
			}

		}
	}

	NetworkImageView imgLargeAds;
	PopupWindow popup;

	private void showPopup(final Activity context) {

		// getApplicationContext());

		int popupWidth = width * 3 / 4; // (int) convertPixelsToDp(480,
		int popupHeight = popupWidth * 4 / 3; // (int) convertPixelsToDp(640,

		// Inflate the popup_layout.xml
		RelativeLayout viewGroup = (RelativeLayout) context
				.findViewById(R.id.popup);

		LayoutInflater layoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View layout = layoutInflater.inflate(R.layout.large_ads, viewGroup);

		imgLargeAds = (NetworkImageView) layout
				.findViewById(R.id.img_large_ads);

		// Creating the PopupWindow
		popup = new PopupWindow(context);
		popup.setContentView(layout);
		popup.setWidth(popupWidth);
		popup.setHeight(popupHeight);
		popup.setTouchable(true);
		popup.setFocusable(false);
		popup.setOutsideTouchable(false);
		popup.setAnimationStyle(R.style.PopupWindowAnimation);

		// Some offset to align the popup a bit to the right, and a bit down,
		// relative to button's position.
		int OFFSET_X = 30;
		int OFFSET_Y = 30;

		// Clear the default translucent background
		popup.setBackgroundDrawable(new BitmapDrawable());

		// Displaying the popup at the specified location, + offsets.
		popup.showAtLocation(layout, Gravity.NO_GRAVITY,
				(width - popupWidth) / 2, (height - popupHeight) / 2);

		// Getting a reference to Close button, and close the popup when
		// clicked.

		ImageView close = (ImageView) layout.findViewById(R.id.close_large_ads);
		close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				popup.dismiss();
			}
		});

		ImageLoader imageLoader = AppController.getInstance().getImageLoader();
		imgLargeAds.setImageUrl(urlImage, imageLoader);
		imgLargeAds.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Toast.makeText(getApplicationContext(), "Click",
				// 1000).show();

				Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(urlApp));
				startActivity(i);

				SharedPreferences.Editor edit = pre.edit();
				edit.putString(KEY_ADS, idApp);
				edit.commit();

				popup.dismiss();
			}
		});

		// videoview.start();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	private void showFragment(int position) {
		Fragment f = null;
		switch (position) {
		case 0:
			f = new HomeFragment();
			tvTitleMenu.setText("HOME");
			break;
		case 1:

			f = new SettingsFragment();
			tvTitleMenu.setText("SETTINGS");
			break;
		case 2:
			f = new SettingsReceiveMsgFragment();
			tvTitleMenu.setText("RECEIVE MESSAGE");
			break;
		case 3:
			f = new SettingsSendMsgFragment();
			tvTitleMenu.setText("SEND MESSAGE");
			break;
		case 4:
			f = new HelpFragment();
			tvTitleMenu.setText("HELPS");
			break;
		case 6:
			Intent intent_more = new Intent(Intent.ACTION_VIEW,
					Uri.parse(getString(R.string.url_more)));
			startActivity(intent_more);

			return;
		case 7:

			Intent intent_rate = new Intent(
					Intent.ACTION_VIEW,
					Uri.parse("https://play.google.com/store/apps/details?id=com.dev.dream.apps.keypadlockscreen"));
			startActivity(intent_rate);

			return;

		case 8:

			Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
					Uri.fromParts("mailto", "iapp.ptit@gmail.com", null));
			emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
					getString(R.string.subject_email));

			startActivity(Intent.createChooser(emailIntent, ""));
			// fragment = new WhatsHotFragment();

			return;
		case 9:
			MyShare.shareTextUrl(Activity.this,
					getString(R.string.message_share),
					getString(R.string.subject_share));
			return;

		default:
			return;
		}
		getSupportFragmentManager().beginTransaction().replace(R.id.content, f)
				.commit();

		viewActionsContentView.showContent();
	}

	public void onActionsButtonClick(View view) {
		if (viewActionsContentView.isActionsShown())
			viewActionsContentView.showContent();
		else
			viewActionsContentView.showActions();
	}

	public void onSourceCodeClick(View view) {

	}

	boolean doubleBackToExitPressedOnce, isShow, askDownload;

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub

		if (doubleBackToExitPressedOnce) {

			handler_timer.removeCallbacks(update_time);

			if (CheckNetword.checkInternetConnection(getApplicationContext())) {
				if (!isShow) {

					isShow = true;
					// Toast.makeText(getApplicationContext(), "show popup",
					// 1000).show();
					showPopupExit(this);

				}
				//
			} else {

				finish();
			}

		}

		this.doubleBackToExitPressedOnce = true;

		Toast.makeText(this, "Please click BACK again to exit",
				Toast.LENGTH_SHORT).show();

		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				doubleBackToExitPressedOnce = false;

			}
		}, 2000);
	}

	ImageView slidingimage;

	private void showPopupExit(final Activity context) {

		int popupWidth = width * 3 / 4; // (int) convertPixelsToDp(480,
		// getApplicationContext());
		int popupHeight = popupWidth / 3 * 4; // (int) convertPixelsToDp(640,
		// getApplicationContext());

		// Inflate the popup_layout.xml
		RelativeLayout viewGroup = (RelativeLayout) context
				.findViewById(R.id.popup_exit);

		LayoutInflater layoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View layout = layoutInflater.inflate(R.layout.popup_exit_layout,
				viewGroup);

		slidingimage = (ImageView) layout.findViewById(R.id.imgExit);

		slidingimage.setBackgroundResource(R.drawable.list_animation0);

		AnimationDrawable rocketAnimation = (AnimationDrawable) slidingimage
				.getBackground();
		rocketAnimation.start();

		// Creating the PopupWindow
		final PopupWindow popup = new PopupWindow(context);
		popup.setContentView(layout);
		popup.setWidth(popupWidth);
		popup.setHeight(popupHeight);
		popup.setTouchable(true);
		popup.setFocusable(false);
		popup.setOutsideTouchable(false);
		popup.setAnimationStyle(R.style.PopupWindowAnimation);

		// Some offset to align the popup a bit to the right, and a bit down,
		// relative to button's position.
		int OFFSET_X = 30;
		int OFFSET_Y = 30;

		// Clear the default translucent background
		popup.setBackgroundDrawable(new BitmapDrawable());

		// Displaying the popup at the specified location, + offsets.
		// popup.showAtLocation(layout, Gravity.NO_GRAVITY,
		// (width - popupWidth) / 2, (height - popupHeight) / 2);

		popup.showAtLocation(layout, Gravity.CENTER, 0, 0);

		// Getting a reference to Close button, and close the popup when
		// clicked.

		TextView txt = (TextView) layout.findViewById(R.id.txtAsk);
		txt.setVisibility(View.GONE);

		if (!pre.getBoolean("rate", false)) {

			Button btnNo = (Button) layout.findViewById(R.id.btnNo);
			btnNo.setVisibility(View.GONE);

			Button btnGood = (Button) layout.findViewById(R.id.btnGood);
			btnGood.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					popup.dismiss();

					SharedPreferences.Editor edit = pre.edit();
					edit.putBoolean("rate", true);
					edit.commit();

					Intent i = new Intent(Intent.ACTION_VIEW, Uri
							.parse(getString(R.string.url)));

					startActivity(i);
					finish();
				}
			});

			Button btnBad = (Button) layout.findViewById(R.id.btnBad);
			btnBad.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					popup.dismiss();

					SharedPreferences.Editor edit = pre.edit();
					edit.putBoolean("rate", true);
					edit.commit();

					// Use your own code here
					Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri
							.fromParts("mailto", "iapp.ptit@gmail.com", null));
					emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
							getString(R.string.subject_email));

					startActivity(Intent.createChooser(emailIntent, ""));

					finish();
				}
			});

			Button btnlater = (Button) layout.findViewById(R.id.btnLate);
			btnlater.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					popup.dismiss();
					finish();
				}
			});
		} else {
			Button btnGood = (Button) layout.findViewById(R.id.btnGood);
			btnGood.setVisibility(View.GONE);
			Button btnlater = (Button) layout.findViewById(R.id.btnLate);
			btnlater.setVisibility(View.GONE);
			Button btnBad = (Button) layout.findViewById(R.id.btnBad);
			btnBad.setVisibility(View.GONE);

			Button btnNo = (Button) layout.findViewById(R.id.btnNo);
			btnNo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					popup.dismiss();

					finish();
				}
			});
		}
		slidingimage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Toast.makeText(getApplicationContext(), "Click",
				// 1000).show();

				Intent i = new Intent(Intent.ACTION_VIEW, Uri
						.parse(getString(R.string.url_more)));
				startActivity(i);

				SharedPreferences.Editor edit = pre.edit();
				edit.putBoolean("click2", true);
				edit.commit();

				// isShow = false;

				// popup.dismiss();
			}
		});

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		handler_timer.removeCallbacks(update_time);

		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		// handler_timer.removeCallbacks(update_time);
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		// handler_timer.postDelayed(update_time, 1000 * 50);

		super.onResume();
	}

}
